package com.handler;

import com.utils.result.Ret;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author xufan
 * @Description:控制器异常类，在控制器中出现异常，自动进行匹配响应的异常方法进行捕获
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    private Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * @author: xufan
     * @Date: 2021/7/27
     * @Description: 控制器异常通用类
     */
    @ExceptionHandler(Exception.class)
    public Ret handleException(Exception e) {
        logger.error(e.getMessage(), e);
        return Ret.fail();
    }

    /**
     * @author: xufan
     * @Date: 2021/7/27
     * @Description: 控制器异常处理参数
     */
    @ExceptionHandler(value = {BindException.class})
    public Ret bindException(BindingResult result) {
        StringBuilder msg = new StringBuilder();
        if (result.hasErrors()) {
            for (ObjectError error : result.getAllErrors()) {
                msg.append(error.getDefaultMessage()).append("|");
            }
        }
        return Ret.fail(msg.toString().substring(0, msg.toString().lastIndexOf("|")));
    }
}
